package com.gzyj.server.factory.jtt808.down;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gzyj.data.common.VehicleIncrement;
import com.gzyj.jtt808.utils.HexBytesUtil;
import com.gzyj.jtt808.v2013.Package;
import com.gzyj.server.config.LogConfig;
import com.gzyj.server.factory.CommonHandler;
import com.gzyj.server.factory.jtt808.NetWorkSerrvice;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class JTT808_0x8106_Handler implements CommonHandler {
    @Override
    public void handler(ChannelHandlerContext ctx, Package msg) throws Exception {

    }

    @Override
    public void handler(ChannelHandlerContext ctx, com.gzyj.jtt808.v2019.Package msg) throws Exception {

    }

    @Override
    public void handler(ChannelHandlerContext ctx, com.gzyj.jtt808.v2011.Package msg) {

    }

    @Autowired
    private NetWorkSerrvice netWorkSerrvice;

    @Override
    public void handler(VehicleIncrement vehicleInfo, String msg) {
        JSONObject command = JSON.parseObject(msg);
        String ipaddress = command.getString("ipAddress");
        Integer seq = command.getIntValue("seq");

        JSONArray array = JSON.parseArray(command.getString("parmIDList"));
        List<Integer> paramList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            paramList.add(array.getIntValue(i));
        }

        if (StringUtils.isNotEmpty(vehicleInfo.getTerminalprotocoltype()) && vehicleInfo.getTerminalprotocoltype().equalsIgnoreCase("2019")) {


        } else {

            com.gzyj.jtt808.v2013.protocol.JTT808_0x8106 jtt808_0x8106=new com.gzyj.jtt808.v2013.protocol.JTT808_0x8106();
            com.gzyj.jtt808.v2013.HeaderMsgBodyProperty headerMsgBodyProperty = new com.gzyj.jtt808.v2013.HeaderMsgBodyProperty();

            headerMsgBodyProperty.setSubcontract(false);
            headerMsgBodyProperty.setEncryptMethod(com.gzyj.jtt808.v2013.HeaderEncryptMethod.None);
            jtt808_0x8106.getPackageHeader().setMsgBodyProperty(headerMsgBodyProperty);
            jtt808_0x8106.getPackageHeader().setTerminalPhoneNo(ipaddress);
            jtt808_0x8106.getPackageHeader().setMsgNum(seq);

            jtt808_0x8106.setParameterCount(paramList.size());
            Integer[] ps=new Integer[paramList.size()];
            paramList.toArray(ps);

            jtt808_0x8106.setParameters(ps);

            ByteBuf data = jtt808_0x8106.encode();

            netWorkSerrvice.send2Veh(ipaddress, data);
            LogConfig.commondLog.info("808 2013版 8106 查询指定终端参数 指令 {} {}", ipaddress, HexBytesUtil.bytesToHex(data.array()));

        }
    }
}
